import { editingLayers } from './common.js';
import { picState } from './api/use-task.js';
import { Layer, useLabelSelector } from './api/use-layer.js';

const startsOrEndsWithNewline = s => s.startsWith('\n') || s.endsWith('\n');

/** 修剪字符串两端的 \n */
const trimNewline = s => s.replace(/^\n+|\n+$/g, () => '');

const elemIndex = elem => Array.from(elem.parentElement.children).indexOf(elem);

/**
 * 偏移后的文本节点
 * @param {Text} node 偏移前的文本节点
 * @param {number} offset 偏移量
 */
function TextSibling(node, offset) {
  const spanElem = node.parentElement;
  const pElem = spanElem.parentElement;
  const newSpanElem = pElem.children[elemIndex(spanElem) + offset];
  return newSpanElem.childNodes[0];
}

const trimmedOffset = content => {
  const newContent = trimNewline(content);
  const start = content.indexOf(newContent);
  const end = (content.length - newContent.length - start) * -1;
  return { start, end };
}

const LabelSelectorPos = spanElem => {
  const rect = spanElem.getBoundingClientRect();

  return {
    top: `${ rect.top + rect.height }px`,
    left: `${ rect.left + rect.width }px`,
  };
}

export function handlePointerMove() {
  addEventListener('pointerup', event => {
    const selection = getSelection();

    // 修剪选中内容首尾换行符，中间的甭管，修剪量用于 setBaseAndExtend 同步视图选中范围
    function setStartAndEnd(content) {
      const offset = trimmedOffset(content);
      selection.setBaseAndExtent(
        TextSibling(selection.anchorNode, offset.start), 0,
        TextSibling(selection.focusNode, offset.end), 1
      );
    }

    R.both(startsOrEndsWithNewline, setStartAndEnd)(selection.toString());

    const startAndEndIndexes = [
      elemIndex(selection.anchorNode.parentElement),
      elemIndex(selection.focusNode.parentElement),
    ];
    editingLayers.value = [Layer(startAndEndIndexes, selection.toString())];
    picState.value.layers.push(...editingLayers.value);
    useLabelSelector( LabelSelectorPos(selection.focusNode.parentElement) );
  }, { once: true });
}
